let enumIdList = new Array();

/**
 * zmn文章模块-文章编辑
 * 文件命名格式：zmn.模块.表/功能.jas
 * @author heguanghua
 * @since 2018/10/18
 */
layui.define(['form', 'layedit', 'laydate'], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let layer = layui.layer;
    let layedit = layui.layedit;
    let laydate = layui.laydate;
    let index;

    form.verify({
        minSort: function(value, item){ //value：表单的值、item：表单的DOM对象
            if (value < 1){
                return "排序号不能小于1";
            }
            if (value > 10000000){
                return "排序号不能大于10000000";
            }
        }, isPositiveNumber: function(value,item){
            if (!/^[0-9]+$/.test(value)) {
                return "排序值只能是正整数";
            }
        },tariffName:function (value) {
            if(!/^[A-Za-z0-9\u4e00-\u9fa5]+$/.test(value)){
                return "计价器名称只能输入字母、数字、汉字";
            }
        }
    });

    zmnLayUtil.layFormVerify(form);

    // 分类下拉框联动
    zmnProduct.laySelectSpecial(form, "/product/listChilds.action", "/product/listCateChilds.action", "/product/listAttrChilds.action", "servCategId", "categOneId", "categId", "attrId");

    // 渠道联动
    form.on("select(channelId)", function (obj) {

        if(json.servProductVO.productType == 2 && $("#channelId").val() == ""){
            $("#channelId").val("");
            form.render("select");
            return layer.alert("请选择使用渠道！");
        }
        if (zmnUtil.isNull(obj) || obj.value == 0) {
            return layer.alert("请选择使用渠道！");
        }
        let channelId = obj.value;
        $.ajax({
            type: "GET", url: "/product/channelDetail.action",
            dataType: "json", data: {channelId: channelId},
            success: function (json) {
                let plat = json.data.plat;

                let showPlat = document.getElementsByName("showPlat");
                for(let k in showPlat){
                    if (showPlat[k].value == plat) {
                        showPlat[k].checked = true;
                    } else {
                        showPlat[k].checked = false;
                    }
                }
                form.render("checkbox");
            }
        });

        if (zmnUtil.isNull(obj) || obj.value == 0 || zmnUtil.isNull($("#categId").val()) || zmnUtil.isNull($("#servCategId").val()) || zmnUtil.isNull($("#categOneId").val())) {
            return;
        }
        $.ajax({
            type: "GET", url: "/product/listAttrChilds.action",
            dataType: "json", data: {categId: $("#categId").val(), categOneId: $("#categOneId").val(), channelId : $("#channelId").val()},
            success: function (items) {
                let optionHtml = loadProductCateg(items);
                $("#attrId").html(optionHtml);
                form.render("radio");
                form.render("checkbox");
            }
        });
    });

    if(json.servProductVO.productId > 0){
        $('#channelId').attr("disabled",true);
    }

    let optionHtml = loadProductCateg(json.attrList);
    $("#attrId").html(optionHtml);

    form.render(null, "zmn-form");

    // 提交
    form.on('submit(zmn-form-submit)', function (obj) {
        let data = obj.field;
        let attrEnumArr = new Array();
        let bizTypeArr = new Array();

        let bizType = document.getElementsByName("bizType");
        for(let k in bizType){
            if(bizType[k].checked)
                bizTypeArr.push(bizType[k].value);
        }

        if(bizTypeArr.length == 0){
            layer.msg("业务类型不能为空");
            return false;
        }
        data.bizType = bizTypeArr.join("$");

        if(!data.tariffStatus){
            layer.msg("计价器状态必选");
            return false;
        }
        // data.showPlat = showPlatArr.join(",");

        for (let i = 0; i < enumIdList.length; i++) {
            let attrId = enumIdList[i];
            let enumId = $('input[name="' + attrId + 'name"]:checked').val();

            if (zmnUtil.isNotNull(enumId)) {
                attrEnumArr.push(attrId + "&" + enumId);
            }
        }

        data.enumIds = attrEnumArr.join(",");

        let url = "/product/addEdit.action";
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            beforeSend: function () {
                index = layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            },
            success: function (json) {
                if(json.status == 200) {
                    layer.msg("操作成功",{time: 1000},()=>{
                        zmnLayUtil.closeThisIframe(parent);
                    });
                } else {
                    layer.msg(json.message, {"icon": 2});
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            },
            complete:function () {
                layer.close(index);
            }
        })

        return false;
    });

    //对外暴露的接口
    exports('product_edit_js', {});
});

var zmnProduct = {
    /**
     * 多级下拉框联动
     * @param form layui.form
     * @param url1 selectOneId请求下级数据的url，返回数据格式 [[value,text], [value,text], [value,text], …]
     * @param url1 selectTwoId请求下级数据的url，返回数据格式 [[value,text], [value,text], [value,text], …]
     * @param selectOneId 第1级select的ID，不含#号
     * @param selectTwoId 第2级select的ID，不含#号
     * @param selectThrId 第3级select的ID，不含#号，如无第3级则两级联动
     */
    laySelectSpecial: function (form, url1, url2, url3, selectOneId, selectTwoId, selectThrId, selectFourId) {
        let $ = layui.$;
        let servCategId;
        let categOneId;
        form.on("select(" + selectOneId + ")", function (obj) {
            if(json.servProductVO.productType == 2 && $("#channelId").val() == ""){
                $("#"+selectOneId).val("");
                form.render("select");
                return layer.alert("请选择使用渠道！");
            }
            if (zmnUtil.isNull(obj) || obj.value == 0) {
                return layer.alert("请选择！");
            }
            servCategId = obj.value;
            $.ajax({
                type: "GET", url: url1,
                dataType: "json", data: {parentId: servCategId},
                success: function (items) {
                    var optionHtml = '<option value="">请选择</option>';
                    for (var i = 0; i < items.length; i++) {
                        optionHtml += '<option value="' + items[i][0] + '">' + items[i][1] + '</option>';
                    }
                    $("#" + selectTwoId).html(optionHtml);
                    form.render("select");
                }
            });
        });
        if (zmnUtil.isEmptyNull(selectThrId)) {
            return;
        }
        ;

        form.on("select(" + selectTwoId + ")", function (obj) {
            if (zmnUtil.isNull(obj) || obj.value == 0) {
                return layer.alert("请选择！");
            }
            categOneId = obj.value;
            servCategId = $('#servCategId').val();
            $.ajax({
                type: "GET", url: url2,
                dataType: "json", data: {categOneId: obj.value, servCategId: servCategId},
                success: function (items) {
                    let optionHtml = '<option value="">请选择</option>';
                    for (var i = 0; i < items.length; i++) {
                        optionHtml += '<option value="' + items[i][0] + '">' + items[i][1] + '</option>';
                    }
                    $("#" + selectThrId).html(optionHtml);
                    form.render("select");
                }
            });
        });

        if (zmnUtil.isEmptyNull(selectFourId)) {
            return;
        }
        ;

        form.on("select(" + selectThrId + ")", function (obj) {
            if (zmnUtil.isNull(obj) || obj.value == 0) {
                return layer.alert("请选择！");
            }
            let data = {categId: obj.value, categOneId: categOneId};
            if(json.servProductVO.productType == 2){
                data = {categId: obj.value, categOneId: categOneId, channelId : $("#channelId").val()};
            }
            $.ajax({
                type: "GET", url: url3,
                dataType: "json", data: data,
                success: function (items) {
                    let optionHtml = loadProductCateg(items);
                    $("#" + selectFourId).html(optionHtml);
                    form.render("radio");
                    form.render("checkbox");
                }
            });
            //服务分类联动前台产品
            $.ajax({
                type: "GET", url: "/product/listShowProducts",
                dataType: "json", data: {servCategId: servCategId,categOneId:categOneId,categId: obj.value},
                success: function (items) {
                    var optionHtml = '<option value="">请选择</option>';
                    for (var i = 0; i < items.length; i++) {
                        optionHtml += '<option value="' + items[i][0] + '">' + items[i][1] + '</option>';
                    }
                    $("#showProductId").html(optionHtml);
                    form.render("select");
                }
            });

            //服务分类联动计价器产品
            $.ajax({
                type: "GET", url: "/product/listTariffProducts",
                dataType: "json", data: {servCategId: servCategId,categOneId:categOneId,categId: obj.value},
                success: function (items) {
                    var optionHtml = '<option value="">请选择</option>';
                    for (var i = 0; i < items.length; i++) {
                        optionHtml += '<option value="' + items[i][0] + '">' + items[i][1] + '</option>';
                    }
                    $("#tariffProductId").html(optionHtml);
                    form.render("select");
                }
            });
        });
    },
}

function loadProductCateg(items) {
    //渲染一级分类数据
    if (zmnUtil.isNull(items)) {
        return "";
    }
    let produHtml = "";
    for (let i = 0; i < items.length; i++) {
        enumIdList.push(items[i].attrId);
        produHtml += '<div class="layui-form-item" pane=""><label class="layui-form-label">' + items[i].name + '：</label>' +
            '<div class="layui-input-block">' + formatterCheckboxValue(items[i].baseCategoryAttributeEnumList, items[i].attrId) + '</div></div>';
    }
    return produHtml;
}

//渲染二级分类数据
function formatterCheckboxValue(baseCategoryAttributeEnumList, attrId) {
    let name = attrId + 'name';
    let checkboxHtml = '<input type="radio" name="' + name + '" lay-skin="primary" value="' + attrId + '" title="无属性值" />';
    if (zmnUtil.isNotNull(json.servProductVO.sequence) && json.servProductVO.sequence.indexOf(attrId) != -1) {
        checkboxHtml = '<input type="radio" name="' + name + '" checked lay-skin="primary" value="' + attrId + '" title="无属性值" />';
    }
    for (let i = 0; i < baseCategoryAttributeEnumList.length; i++) {
        if (zmnUtil.isNotNull(json.servProductVO.sequence) && json.servProductVO.sequence.indexOf(baseCategoryAttributeEnumList[i].enumId) != -1) {
            checkboxHtml += '<input type="radio" name="' + name + '" lay-skin="primary" checked value="' + baseCategoryAttributeEnumList[i].enumId + '" title="' + baseCategoryAttributeEnumList[i].enumValue + '" />'
        } else {
            checkboxHtml += '<input type="radio" name="' + name + '" lay-skin="primary" value="' + baseCategoryAttributeEnumList[i].enumId + '" title="' + baseCategoryAttributeEnumList[i].enumValue + '" />'
        }
    }
    return checkboxHtml;
}